package com.yunbiao.ybbusstopplate.refactoring.ui.fengxian;

import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.UiMessageUtils;
import com.bumptech.glide.Glide;
import com.example.library_hy_advert.system.Cache;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.BaseFragment;
import com.yunbiao.ybbusstopplate.base.BaseSettingFragment;
import com.yunbiao.ybbusstopplate.databinding.FragmentFengxianHeadInformationBinding;
import com.yunbiao.ybbusstopplate.refactoring.Config;
import com.yunbiao.ybbusstopplate.refactoring.ui.dalian.ZHIDAParser;
import com.yunbiao.ybbusstopplate.refactoring.serial.SerialPortServices;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FengxianHeadInformationFragment extends BaseFragment {

    private FragmentFengxianHeadInformationBinding binding;

    @Override
    public int getViewId() {
        return R.layout.fragment_fengxian_head_information;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.bind(requireView());

        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_LINE_NAME.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_START_END.getType(),uiMessageCallback);

        initConfigUI();

        binding.vSetting.setOnClickListener(v -> {
            FragmentUtils.add(getChildFragmentManager(),new FengxianSettingFragment(),binding.flSetting.getId());
        });
    }

    @Override
    protected void initData() {
        SerialPortServices.start();
    }

    private void initConfigUI(){
        String companyIcon = Cache.getString(Config.Key.COMPANY_ICON.name());
        if(!TextUtils.isEmpty(companyIcon)){
            Glide.with(binding.ivCompanyIcon).asBitmap().load(companyIcon).into(binding.ivCompanyIcon);
        }

        String companyName = Cache.getString(Config.Key.COMPANY_NAME.name());
        binding.tvCompanyName.setText(companyName);
    }

    private final List<ZHIDAParser.Site> siteList = new ArrayList<>();

    private final UiMessageUtils.UiMessageCallback uiMessageCallback = uiMessage -> {
        int id = uiMessage.getId();
        Object object = uiMessage.getObject();

        if(id == ZHIDAParser.Event.UPDATE_LINE_NAME.getType()){
            binding.tvLineName.setText(object.toString());
        } else if(id == ZHIDAParser.Event.UPDATE_SITE_LIST.getType()){
            ZHIDAParser.Site[] sites = (ZHIDAParser.Site[]) object;
            siteList.addAll(Arrays.asList(sites));

            if (!siteList.isEmpty()) {
                ZHIDAParser.Site site = siteList.get(siteList.size() - 1);
                binding.tvDriveDirection.setText(site.getChName());
            }
        } else if(id == ZHIDAParser.Event.BROAD_SITE.getType()){
            Object[] objects = (Object[]) object;
            int siteIndex = (int) objects[1];
            String inOut = (String) objects[2];

            ZHIDAParser.Site preSite = null;
            ZHIDAParser.Site currSite = null;
            ZHIDAParser.Site nextSite = null;
            for (ZHIDAParser.Site site : siteList) {
                if(site.getIndex() == siteIndex){
                    currSite = site;
                } else if(site.getIndex() == siteIndex - 1){
                    preSite = site;
                } else if(site.getIndex() == siteIndex + 1){
                    nextSite = site;
                }
            }

            binding.tvPreSiteCh.setText(preSite == null ? "" : preSite.getChName());
            binding.tvPreSiteEn.setText(preSite == null ? "" : preSite.getEnName());

            binding.tvCurrSiteCh.setText(currSite == null ? "" : currSite.getChName());
            binding.tvCurrSiteEn.setText(currSite == null ? "" : currSite.getEnName());

            binding.tvNextSiteCh.setText(nextSite == null ? "" : nextSite.getChName());
            binding.tvNextSiteEn.setText(nextSite == null ? "" : nextSite.getEnName());

            if("00".equals(inOut)){
                binding.tvInoutStatusCh.setText("当前到站");
                binding.tvInoutStatusEn.setText("We are now arriving at");
                binding.tvInoutStatusCh.setTextColor(requireContext().getResources().getColor(android.R.color.holo_orange_dark));
                binding.tvInoutStatusEn.setTextColor(requireContext().getResources().getColor(android.R.color.holo_orange_dark));
            } else {
                binding.tvInoutStatusCh.setText("下一站");
                binding.tvInoutStatusEn.setText("Next stop is");
                binding.tvInoutStatusCh.setTextColor(requireContext().getResources().getColor(android.R.color.holo_green_dark));
                binding.tvInoutStatusEn.setTextColor(requireContext().getResources().getColor(android.R.color.holo_green_dark));
            }

            if(currSite != null){
                binding.llBroadSite.setVisibility(View.VISIBLE);
                binding.tvBroadCurrSite.setText(currSite.getChName());
                if(TextUtils.equals("00",inOut)){
                    binding.tvSiteInOut.setText("到了");
                } else if(TextUtils.equals("01",inOut)){
                    binding.tvSiteInOut.setText("下一站");
                }
                binding.llBroadSite.postDelayed(() -> {
                    binding.tvBroadCurrSite.setText("");
                    binding.llBroadSite.setVisibility(View.GONE);
                },5000);
            }


        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        SerialPortServices.stop();

        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_LINE_NAME.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_START_END.getType(),uiMessageCallback);
    }

    private long mExitTime = 0;
    @Override
    public boolean onBackClick() {
        List<Fragment> fragments = FragmentUtils.getFragments(getChildFragmentManager());
        for (int i = fragments.size() - 1; i >= 0; i--) {
            Fragment fragment = fragments.get(i);
            if(fragment instanceof BaseSettingFragment){
                FragmentUtils.remove(fragment);
                initConfigUI();
                return true;
            }
        }
        return false;
    }
}
